﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OperaHouse.Repository.News;
using OperaHouse.DAL.Infrastructure;
using OperaHouse.Domain.News;
using OperaHouse.Common;

namespace OperaHouse.Business.News
{
    public partial class NewsService : INewsService
    {
        #region Fields

        private readonly INewsRepository _newsRepository;
        private readonly IUnitOfWork _unitOfWork;

        #endregion

        #region Ctor

        public NewsService(INewsRepository newsRepository, IUnitOfWork unitOfWork)
        {
            this._newsRepository = newsRepository;
            this._unitOfWork = unitOfWork;
        }

        #endregion

        #region Methods
        public virtual IList<NewsItem> GetAllNewsItems()
        {
            return _newsRepository.GetAll().ToList();
        }

        public Common.IPagedList<NewsItem> GetAllNews(bool? ispublished, int pageIndex, int pageSize)
        {
            var query = _newsRepository.Table;

            if (ispublished != null)
            {
                query = query.Where(n => n.Published);
            }

            query = query.OrderByDescending(u => u.CreatedOn);

            var news = new PagedList<NewsItem>(query, pageIndex, pageSize);
            return news;
        }

        public NewsItem GetNewsById(int id)
        {
            return _newsRepository.GetById(id);
        }

        public void InsertNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");

            _newsRepository.Insert(news);
            _unitOfWork.Commit();
        }

        public void UpdateNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");

            _newsRepository.Update(news);
            _unitOfWork.Commit();
        }

        public void DeleteNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");

            _newsRepository.Delete(news);
            _unitOfWork.Commit();
        }
        #endregion
    }
}
